﻿using Core.Enums;
using Core.Interfaces;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;

namespace Core.Com
{
    /// <summary>
    /// 系统上下文信息
    /// </summary>
    public class SystemContext
    {


        private static SystemContext _Current = null;
        private SystemContext()
        {
        }
        /// <summary>
        /// 当前系统上下文
        /// </summary>
        public static SystemContext Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new SystemContext();

                    //Logger.LoggerPost = (logcontent) => {
                    //    Logger.Post(_Current.Config.SAASUrl + "/Track/Debug", logcontent, 5000);
                    //};
                    if (_Current.Iots == null)
                    {
                        _Current.Iots = new List<Lazy<IIot, IIotData>>();
                    }
                    _Current.Compose();
                }
                return _Current;
            }
        }

        /// <summary>
        /// 导入部件
        /// </summary>
        [ImportMany]
        public IEnumerable<Lazy<IIot, IIotData>> Iots { get; set; }

        /// <summary>
        /// 组合部件
        /// </summary>
        public void Compose()
        {
            try
            {
                var catelog = new AggregateCatalog();
                string iotPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Iots");
                if (Directory.Exists(iotPath))
                {
                    var dc = new DirectoryCatalog("Iots","*.exe");
                    catelog.Catalogs.Add(dc);
                }
                //var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(o => o.FullName.Contains("Iot")).ToList();
                //foreach (var assembly in assemblies)
                //{
                //    catelog.Catalogs.Add(new AssemblyCatalog(assembly));
                //}
                var container = new CompositionContainer(catelog);
                container.ComposeParts(this);
            }
            catch (ReflectionTypeLoadException ex)
            {
                throw ex;
            }
        }

        private SystemConfig _Config = null;
        /// <summary>
        /// 系统配置
        /// </summary>
        public SystemConfig Config
        {
            get
            {
                if (_Config == null)
                {
                    _Config = ConfigLoadFile();
                }
                return _Config;
            }
            set
            {
                _Config = value;
            }
        }
        /// <summary>
        /// 从本地文件加载配置
        /// </summary>
        /// <returns></returns>
        public SystemConfig ConfigLoadFile()
        {
            var config = new SystemConfig();
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SystemConfig.json");
            if (File.Exists(path))
            {
                var json = File.ReadAllText(path);
                if (!String.IsNullOrEmpty(json))
                {
                    config = JsonConvert.DeserializeObject<SystemConfig>(json);
                }
            }
            //config.GetSettingFunc = new Func<string, string>((name) =>
            //{
            //    if (String.IsNullOrEmpty(config.LocalData))
            //    {
            //        return null;
            //    }
            //    using (SqlConnection conn = new SqlConnection(config.LocalData))
            //    {
            //        conn.Open();
            //        var row = conn.Query<dynamic>("select * from [Settings] where Name=@Name", new { Name = name }).FirstOrDefault();
            //        if (row != null)
            //        {
            //            return (string)row.Value;
            //        }
            //        conn.Close();
            //    }
            //    return null;
            //});
            return config;
        }
        private SystemSettings _Settings = null;
        /// <summary>
        /// 系统设置
        /// </summary>
        public SystemSettings Settings
        {
            get
            {
                if (_Settings == null)
                {
                    _Settings = new SystemSettings();
                }
                return _Settings;
            }
            set
            {
                _Settings = value;
            }
        }
        /// <summary>
        /// 保存配置到本地文件
        /// </summary>
        public void ConfigSaveToFile()
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SystemConfig.json");
            var json = JsonConvert.SerializeObject(this.Config, Formatting.Indented, Settings.JSONSerializeSettings);
            if (!String.IsNullOrEmpty(json))
            {
                File.WriteAllText(path, json);
            }
        }



        /// <summary>
        /// 获取扩展对象
        /// </summary>
        /// <typeparam name="T">继承自IExtention的接口</typeparam>
        /// <param name="type">接口类型</param>
        /// <param name="name">接口名</param>
        /// <returns></returns>
        public T GetIot<T>(IotType type, string name)
        {
            var extention = SystemContext.Current.Iots.FirstOrDefault(o => o.Metadata.Type == type && o.Metadata.Name == name);
            if (extention != null && extention.Value != null && extention.Value is T)
            {
                return (T)extention.Value;
            }
            return default(T);
        }
        ///// <summary>
        ///// 阅读设备
        ///// </summary>
        //public IReader Reader
        //{
        //    get
        //    {
        //        return GetIot<IReader>(IotType.Reader, SystemContext.Current.Config.Reader);
        //    }
        //}

        private SystemSession _Session = null;
        /// <summary>
        /// 会话数据
        /// </summary>
        public SystemSession Session
        {
            get
            {
                if (_Session == null)
                {
                    _Session = new SystemSession();
                }
                return _Session;
            }
            set
            {
                _Session = value;
            }

        }
        public string IPAddress
        {
            get {

                try
                {
                    string HostName = Dns.GetHostName(); //得到主机名
                    IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                    for (int i = 0; i < IpEntry.AddressList.Length; i++)
                    {
                        //从IP地址列表中筛选出IPv4类型的IP地址
                        //AddressFamily.InterNetwork表示此IP为IPv4,
                        //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                        if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                        {
                            return IpEntry.AddressList[i].ToString();
                        }
                    }
                    return "";
                }
                catch (Exception ex)
                {
                    ("获取本机IP出错:" + ex.Message).Log("ERROR");
                    return "";
                }

            }
        }
    }
}
